/**
 * Created by Administrator on 2015/12/8.
 */
app.factory('GridFactory', ['httpWrapService', '$filter', function (httpWrapService, $filter) {
    function Grid(config){
        var grid = this;
        this.config = config;

        this.url = config.url;
        this.isFirstLoadSuccessCallbak = false;
        this.loadSuccessCallbak = config.loadSuccessCallbak;
        this.params = config.params || {};

        this.columnDefs = [];
        this.deletes = {};
        this.externalParams = {
            sort : [],
            filter : [],
            pageSize : 50,
            pageNumber: 1
        },
        this.gridOptions = {
            columnDefs: this.columnDefs,
            enableColumnResizing: true,
            enableFiltering: true,
            enableFullRowSelection: true,
            multiSelect : false,
            paginationPageSizes: [10, 25, 50, 75],
            paginationPageSize: 50,
            data : [],
            onRegisterApi : function(gridApi){
                grid.api = gridApi;

                // 扩展排序
                if(grid.gridOptions.useExternalSorting) {
                    grid.api.core.on.sortChanged(null, function(g, sortColumns, i) {
                        if (sortColumns.length == 0) {
                            grid.externalParams.sort = [];
                        } else {
                            grid.externalParams.sort = [];
                            for(var i = 0; i < sortColumns.length; i++) {
                                grid.externalParams.sort[i] = {
                                    field: sortColumns[i].field,
                                    direction : sortColumns[i].sort.direction,
                                    priority : sortColumns[i].sort.priority
                                }
                            }
                        }
                        // 排序参数改变后，重新装载数据
                        grid.load();
                    });
                }

                // 扩展分页 排序为后台
                if(grid.gridOptions.useExternalPagination) {
                    grid.api.pagination.on.paginationChanged(null, function (newPage, pageSize) {
                        grid.externalParams.pageNumber = newPage;
                        grid.externalParams.pageSize = pageSize;
                        // 分页参数修改重新装载数据
                        grid.load();
                    });
                }

                // 扩展过滤，保存参数
                if(grid.gridOptions.useExternalFiltering) {
                    grid.api.core.on.filterChanged(null, function(b,f) {
                        grid.externalParams.filter = [];
                        var index = 0;
                        for(var i = 0; i < grid.api.grid.columns.length; i++) {
                            // 遍历列
                            var col = grid.api.grid.columns[i];
                            if(col.filters.length > 0) {
                                for(var j = 0; j < col.filters.length; j++) {
                                    // 取得所有过滤器
                                    var f = col.filters[j];
                                    if (f.term || false === f.term) {
                                        var value = f.term;
                                        if(angular.isDate(f.term) && f.format) {
                                            value = $filter('date')(f.term, f.format);
                                        }
                                        grid.externalParams.filter[index++] = {
                                            field: col.field,
                                            term: value,
                                            type: f.type
                                        }
                                    }
                                }
                            }
                        }

                        // 延迟加载
                        if(grid.timename) {
                            clearTimeout(grid.timename);
                        }
                        grid.timename = setTimeout(function(){
                            grid.load();
                        },1500);

                    });
                }

            }
        };
        angular.extend(this.columnDefs, this.config.columnDefs);
        angular.extend(this.gridOptions, this.config.gridOptions);
    }



    Grid.prototype = {
        /**
         * 装载表格数据
         */
        load: function () {
            var grid = this;
            // 读取查询参数
            var data = angular.copy({
                params : grid.params
            }, {});
            // 读取分页、排序、过滤参数
            if(grid.gridOptions.useExternalPagination) {
                angular.extend(data, {
                    externalParams : grid.externalParams
                });
            }
            httpWrapService.post(grid.url, data).then(function(res){
                    // 处理后台分页
                    if(grid.gridOptions.useExternalPagination) {
                        grid.gridOptions.totalItems = res.data.page.total;
                        grid.gridOptions.data = res.data.page.rows;
                    } else {
                        grid.gridOptions.data = res.data.data;
                    }

                    // 装载成功后回调
                    if(grid.loadSuccessCallbak) {
                        grid.loadSuccessCallbak(res);
                        if(grid.isFirstLoadSuccessCallbak) {
                            grid.loadSuccessCallbak = null;
                        }
                    }
                });
        },

        /**
         *  调整表格窗体大小
          */
        resize : function(){
            var grid = this;
            setTimeout(function(){
                grid.api.core.handleWindowResize();
            },400)
        },
        /**
         * 根据ID列表选中数据行
         * @param ids
         */
        selectRows : function(ids){
            for(var i = 0; i < this.gridOptions.data.length; i ++) {
                var row = this.gridOptions.data[i];
                if(ids[row.id]) {
                    this.api.selection.selectRow(row);
                }
            }
        },

        /**
         * 获取选中的数据行
         * @returns {*}
         */
        getSelectedRows : function(){
            return this.api.selection.getSelectedRows();
        },

        /**
         * 删除表格中的数据行
         * @param row
         */
        deleteRow: function (row) {
            var index = this.gridOptions.data.indexOf(row);
            this.gridOptions.data.splice(index, 1);
        }


    }
    /**
     * 新建实例
     * @param config
     * @returns {Grid}
     */
    Grid.newInstance = function(config){
        return new Grid(config);
    }

    return {
        newInstance : function(config){
            return Grid.newInstance(config);
        }
    };
}]);